package com.me.study.javaCore.script;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import java.util.List;

public class TestNashorn {

    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> factories = manager.getEngineFactories();
        for (ScriptEngineFactory factory : factories) {
            System.out.println(factory.getEngineName());
        }

        ScriptEngine engine = manager.getEngineByName("nashorn");

        // 执行 js
        engine.eval("print('Hello, World')");// 执行js

        // 执行脚本文件
        // engine.eval(new java.io.FileReader("script.js"));

        // 把 java对象设置为 js全局变量
        engine.put("global", TestNashorn.class.getName());

        // 调用 js方法
        engine.eval("function hello(name) { print('Hello, ' + name); print('Hello, ' + global); }");// 定义 js方法
        Invocable inv = (Invocable) engine;// 创建 Invocable
        inv.invokeFunction("hello", "Scripting!");// 调用 js方法

    }

}
